#include "board.h"
#include<QPainter>
#include<QMouseEvent>

Board::Board(QWidget *parent) : QWidget(parent)
{
   for(int i=0;i<32;i++){
    _s[i].init(i);
   }
   _selectid=-1;
}
Board::~Board(){

}
void Board::paintEvent(QPaintEvent *){
    QPainter painter(this);
    int d=40;
    _r=d/2;
    //画10条横线
    for(int i=1;i<=10;i++){
        painter.drawLine(QPoint(d,i*d),QPoint(9*d,i*d));
    }
    //画9条竖线
    for(int i=1;i<=9;i++){
        if(i==1||i==9){
            painter.drawLine(QPoint(i*d,d),QPoint(i*d,10*d));
        }
        else{
            painter.drawLine(QPoint(i*d,d),QPoint(i*d,5*d));
            painter.drawLine(QPoint(i*d,6*d),QPoint(i*d,10*d));
        }
    }
    //画九宫格
    painter.drawLine(QPoint(4*d,1*d),QPoint(6*d,3*d));
    painter.drawLine(QPoint(6*d,1*d),QPoint(4*d,3*d));
    painter.drawLine(QPoint(4*d,8*d),QPoint(6*d,10*d));
    painter.drawLine(QPoint(6*d,8*d),QPoint(4*d,10*d));

    //绘制棋子
    for(int i=0;i<32;i++){
        drawqizi(painter,i);
    }
}
QPoint Board::center(int row,int col){
    QPoint ret;
    ret.rx()=(col+1)*_r*2;
    ret.ry()=(row+1)*_r*2;
    return ret;
}
QPoint Board::center(int id){
    return center(_s[id]._row,_s[id]._col);
}

void Board::drawqizi(QPainter &painter,int id){
    QPoint c=center(id);
    QRect rect=QRect(c.x()-_r,c.y()-_r,_r*2,_r*2);

    if(id==_selectid){
        painter.setBrush(QBrush(Qt::gray));
    }
    else{
        painter.setBrush(QBrush(Qt::yellow));
    }

    painter.setPen(Qt::black);
    painter.drawEllipse(center(id),_r,_r);
    if(_s[id]._red){
    painter.setPen(Qt::red);
    }
    painter.setFont(QFont("system",_r,700));
    painter.drawText(rect,_s[id].getText(),QTextOption(Qt::AlignCenter));
}
bool Board::getRowCol(QPoint pt, int &row, int &col){
    for(row=0;row<=9;row++){
        for(col=0;col<=8;col++){
            QPoint c=center(row,col);
            int dx=c.x()-pt.x();
            int dy=c.y()-pt.y();
            int dist=dx*dx+dy*dy;
            if(dist<_r*_r){
                return true;
            }
        }
    }
    return false;
}

void Board::mouseReleaseEvent(QMouseEvent *ev){
    QPoint pt=ev->pos();
    //将pt转化为象棋行列值
    //判断行列值上有无棋子
    int row,col;
    bool bRet=getRowCol(pt,row,col);
    if(bRet==false){//点到棋盘外
        return;
    }
    int i;
    for(i=0;i<32;i++){
        if(_s[i]._row==row&&_s[i]._col==col&&_s[i]._dead==false){
            break;
        }
    }
    if(i<32){
        _selectid=i;
        update();
    }

}
